import { t } from 'i18next'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { ViewRef } from '../vmp/VmpView/interface'
import { PollRef } from '../vmp/VmpPoll'
import { PlanRef } from '../vmp/VmpPlan'
import { FontSettingRef } from '../vmp/FontSetting'
import { transVmpDTO } from '../vmp/translator'
import { Alert } from '@/components/Alert'
import { useRequest } from 'ahooks'
import { useMccStore } from '../../store'
import { Message, MessageFunctionType } from '@kedacom/react-next'
import { fetchChangeMTVmp, fetchGetMtVmpParam, fetchStartMTVmp, fetchStopMTVmp } from '@/api/manager/mtVmp'
import { revert_vmp, Vmp } from '../vmp/interface'
import shallow from 'zustand/shallow'
import { getItemByMtKey } from '@/pages/manager/blocks/main/table/all/utils'
import { useTableAllStore } from '../main/table/all/store'
import { useMtVmpStore } from './store'
import { useManagerStore } from '../main/manager/store'
import { ChairmanVmpData } from '@/api/manager/mtVmp/interface'
import { Mt } from '@/api/manager/mt'
import useLock from '@/hooks/useLock'
import { actionButtonsCancel } from '../../store.actionButton'

export default function useService() {
	const { meetingType, meetingMoid } = useMccStore(
		(state) => ({
			meetingType: state.mccInfo.meetingType,
			meetingMoid: state.mccInfo.meetingMoid,
		}),
		shallow
	)
	const {
		_isStart,
		_isEdit,
		_preData,
		data,
		updateData,
		update,
		onClose: closeCb,
		onInit,
		mtid,
		_setSessionStage,
		_getSessionStage,
	} = useMtVmpStore((state) => ({
		_isStart: state._isStart,
		_isEdit: state._isEdit,
		_preData: state._preData,
		data: state.data,
		updateData: state.updateData,
		update: state.update,
		onClose: state.onClose,
		onInit: state.onInit,
		mtid: state.mt_info?.mtid || '',
		_getSessionStage: state._getSessionStage,
		_setSessionStage: state._setSessionStage,
	}))
	const tableAll = useTableAllStore((state) => state.tree)
	useEffect(() => {
		if (tableAll) {
			const _tree = getItemByMtKey(tableAll, '0.0.0.0_0')
			const _tree_all: Mt[] = _tree?.children.filter((item) => item.mcc.isMt).map((v) => v.mcc as Mt) || []
			update({
				batchMembers: _tree_all,
			})
		}
	}, [tableAll])
	const disabled = useMemo(() => _isStart && !_isEdit, [_isStart, _isEdit])
	const loadMaskRef = useRef<ReturnType<MessageFunctionType> | null>(null)
	const viewRef = useRef<ViewRef | null>(null)
	const pollRef = useRef<PollRef | null>(null)
	const planRef = useRef<PlanRef | null>(null)
	const fontSettingRef = useRef<FontSettingRef | null>(null)
	const [pollMembersSearchText, setPollMembersSearchText] = useState('')
	useEffect(() => {
		loadMaskRef.current = Message.loading(t('正在加载管理方画面合成信息，请稍候……'))
		onInit()
	}, [])
	useRequest(() => fetchGetMtVmpParam(meetingMoid, mtid), {
		onSuccess: (res) => {
			loadMaskRef.current?.hide() //隐藏蒙层
			if (res && res.success) {
				const _stage = _getSessionStage() /**缓存数据*/
				if (res.data || !_stage) {
					/**（1）处于画面合成当中 （2）不处于画面合成当中缓存为空*/
					let _data = res.data ? new Vmp(res.data) : null
					/**新增将编辑状态变为false*/
					update({
						_isStart: !!_data,
						_preData: res.data ?? null,
						_isEdit: false,
					})
					updateData(_data)
					_setSessionStage(res.data)
				} else {
					update({ _isStart: false, _isEdit: false, _preData: null })
					updateData(new Vmp(_stage))
				}
			} else {
				Alert(res.description || '')
			}
		},
		onFinally: () => {
			loadMaskRef.current?.hide() //隐藏蒙层
		},
	})
	const startVmp = useLock(
		async () => {
			//todo 暂且认为管理方切换不存在，不过多处理这块逻辑
			let chairman = useManagerStore.getState().chairman
			if (!chairman?.mtKey) {
				Alert(t('请设置当前会议管理方'))
				return
			}
			if (!chairman.status.isOnline) {
				Alert(t('当前会议管理方已离线'))
				return
			}
			let param = getVmpParam()
			if (!param) return
			let _data = Object.assign({}, transVmpDTO(revert_vmp(param)), {
				vmp_mt: { mt_id: mtid },
				broadcast: 0,
			}) as unknown as ChairmanVmpData
			let msg = Message.loading(t('正在处理，请稍候……'))
			if (_isStart) {
				fetchChangeMTVmp(meetingMoid, mtid, _data).then((res) => {
					msg.hide()
					if (res.success) {
						update({ _isEdit: false, _message_flag: 'mtVmp_manager_apply' })
					} else {
						Alert(res.description ?? t('编辑管理方画面合成失败'))
					}
				})
			} else {
				fetchStartMTVmp(meetingMoid, _data).then((res) => {
					msg.hide()
					if (res.success) {
						update({ _isEdit: false, _message_flag: 'mtVmp_manager_start' })
					} else {
						Alert(res.description ?? t('开启管理方画面合成失败'))
					}
				})
			}
		},
		1000,
		true
	)
	const stopVmp = useLock(
		async () => {
			let msg = Message.loading(t('正在处理，请稍候……'))
			fetchStopMTVmp(meetingMoid, mtid).then((res) => {
				msg.hide()
				if (res && res.success) {
					update({ _message_flag: 'mtVmp_manager_stop' })
				} else {
					Alert(res.description ?? t('操作失败'))
				}
			})
		},
		1000,
		true
	)
	const saveTempVmp = async () => {
		Message.info(t('设置已保存'))
	}
	const getVmpParam = () => {
		if (data.mode === 4 && !pollRef.current?.testValue()) return null
		const vmpParam: Vmp = {
			mt_name_style: {
				font_color: fontSettingRef.current?.getValue().fontColor ?? '#FFFFFF',
				font_size: fontSettingRef.current?.getValue().size ?? 1,
				position: fontSettingRef.current?.getValue().position ?? 1,
			},
			poll: pollRef.current?.getValue(),
			id: planRef.current?.getValue().value === '0' ? '' : planRef.current?.getValue().value ?? '',
			name: planRef.current?.getValue().value === '0' ? '' : planRef.current?.getValue().label ?? '',
			layout: data.mode === 2 ? 0 : viewRef.current?.getStyle() ?? 0,
			members: viewRef.current?.getValue() ?? [],
			broadcast: data.broadcast,
			except_self: data.except_self,
			mode: meetingType === 2 ? 1 : data.mode,
			show_mt_name: data.show_mt_name,
			voice_hint: data.voice_hint,
		}
		updateData(vmpParam)
		return vmpParam
	}
	const onClose = () => {
		if (_isEdit && _isStart) {
			//退出编辑
			update({ _isEdit: false })
			//恢复数据
			updateData(_preData ? new Vmp(_preData) : null)
		} else {
			// 关闭
			update({ isOpen: false })
			closeCb()
		}
	}
	const onIconClose = async () => {
		/**先点管理方轮询  再点管理方画面合成 底部按钮未取消 */
		useMccStore.getState().setCurPage('mcc_main')
		actionButtonsCancel()
		/**第一种：如果当前接口状态为1  则取当前的接口数据作为缓存;第二种否则取页面缓存*/
		let _flag = false
		const res = await fetchGetMtVmpParam(meetingMoid, mtid) /**获取接口数据*/
		if (res && res.success) {
			if (res.data) {
				/**data存在值就证明当前的终端的画面合成状态已开启*/
				_setSessionStage(res.data) // 缓存更新
				update({ isOpen: false })
				closeCb()
				_flag = true
			}
		}
		if (_flag) return
		// (2) 第二种
		/**返回保存可以开启画面合成参数*/
		let param = getVmpParam() /**获取当前页面数据 */
		if (!param) return
		_setSessionStage(revert_vmp(param))
		update({ isOpen: false })
		closeCb()
	}
	const EditVmp = () => {
		if (!_isStart) return
		if (_isEdit) {
			//应用
			startVmp()
		} else {
			//编辑
			update({ _isEdit: true })
		}
	}
	const handleApplyVmp = () => {
		if (!_isStart && !_isEdit) return
		startVmp()
		update({ _message_flag: 'mtVmp_manager_apply' })
	}
	const handleCancelVmpEdit = () => {
		if (!_isStart && !_isEdit) return
		update({ _isEdit: false })
		//恢复数据
		updateData(_preData ? new Vmp(_preData) : null)
	}
	return {
		/** 是否处于禁止状态 */
		disabled,
		viewRef,
		pollRef,
		planRef,
		fontSettingRef,
		/** 获取最新画面合成参数 */
		getVmpParam,
		/** 开始画面合成 */
		startVmp,
		/** 结束画面合成 */
		stopVmp,
		/** 编辑画面合成 */
		EditVmp,
		/** 取消方法 */
		onClose,
		/** 右上角x方法 */
		onIconClose,
		/**保存为临时参数 */
		saveTempVmp,
		handleApplyVmp,
		/**取消编辑 */
		handleCancelVmpEdit,
		/**批量轮询搜索文本 */
		pollMembersSearchText,
		/**设置批量轮询搜索文本 */
		setPollMembersSearchText,
	}
}
